package com.htandroid.htandroid.aty;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ab.soap.AbSoapListener;
import com.ab.soap.AbSoapParams;
import com.ab.soap.AbSoapUtil;
import com.ab.task.AbTask;
import com.ab.task.AbTaskItem;
import com.ab.task.AbTaskObjectListener;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.ioc.AbIocView;
import com.google.gson.Gson;
import com.htandroid.htandroid.R;
import com.htandroid.htandroid.adapter.MainItemGridAdapter;
import com.htandroid.htandroid.entity.UffjOptions;
import com.htandroid.htandroid.entity.UserAuth;
import com.htandroid.htandroid.global.MyApplication;
import com.htandroid.htandroid.sys.InstorageURL;
import com.htandroid.htandroid.sys.User;
import com.htandroid.htandroid.tools.MyStringUtil;
import com.htandroid.htandroid.tools.ToolLog;
import com.htandroid.htandroid.views.MyPopupWindow;
import com.htandroid.reconstitute.base.ConstanceHeTai;
import com.htandroid.reconstitute.base.ConstanceHttp;
import com.htandroid.reconstitute.entity.ParamsSettingBean;
import com.htandroid.reconstitute.entity.UserPermissionBean;
import com.htandroid.reconstitute.utils.SpUtil;
import com.htandroid.reconstitute.utils.ToastUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;

import static com.htandroid.htandroid.constance.ConstanceServer.BaseUrl_New;

public class MainActivity extends MyBaseActivity {
    public MyApplication myApplication; //全局变量application
    private String regId1 = "";
    private String authmenus = "";
    private ArrayList<UffjOptions> optionslist;//参数设置
    private ArrayList<UserAuth> userauthlist;//用户权限
    private String mrqgd_usesp = "false";
    public static boolean isForeground = false;
    private static boolean isJtgl = false;
    private AbSoapUtil mAbSoapUtil = null;
    private String isModule0 = "false";
    private JiGuangReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = ".aty.MESSAGE_RECEIVED_ACTION";
    @AbIocView(id = R.id.ll_main)
    LinearLayout ll_main;
    private LayoutInflater inflater;
    private LinearLayout.LayoutParams params;
    private MyPopupWindow popupWindow;
    private boolean popShow;

    private String cacc_id = "";
    private String yearStr = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.activity_main);

        regId1 = getIntent().getStringExtra("regId1");
        cacc_id = getIntent().getStringExtra("caccIdStr");
        yearStr = getIntent().getStringExtra("yearStr");


        titleBar.setTitleText(R.string.htsoft);
        titleBar.setLogo(R.mipmap.user);
        titleBar.setLogoOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showUserInfo();
            }
        });
        myApplication = (MyApplication) abApplication;//获得我们的应用程序全局变量
        mAbSoapUtil = AbSoapUtil.getInstance(this);
        mAbSoapUtil.setTimeout(10000);
        czzcorp_list();
        getAuth();
        getdata();





    }

    //显示用户信息
    private void showUserInfo() {
        if (popupWindow == null) {
            View popupWview = inflater.inflate(R.layout.popup_window, null);
            ((TextView) popupWview.findViewById(R.id.tv_user)).setText(myApplication.mSharedPreferences.getString("LOGIN_USER_NAME", ""));
            TextView caccTv = (TextView) popupWview.findViewById(R.id.tv_cacc);
            caccTv.setText("账套信息:" + myApplication.mSharedPreferences.getString("cacc_name", ""));
            caccTv.setSelected(true);
            String timeStr = myApplication.mSharedPreferences.getString("ciyear", "");
            if (MyStringUtil.equals(timeStr.trim(), Calendar.getInstance().get(Calendar.YEAR) + "")) {
                timeStr = MyStringUtil.getTimeStr(System.currentTimeMillis(), MyStringUtil.TIME_FORMAT_ONE);
            } else {
                timeStr = timeStr.trim() + "-01-01";
            }
            ((TextView) popupWview.findViewById(R.id.tv_time)).setText("最近登录时间:" + timeStr);
            popupWview.findViewById(R.id.ll_exit).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(MainActivity.this, Login.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK));
                }
            });
            popupWindow = new MyPopupWindow(popupWview, ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT, true);
            popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            popupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
            popupWindow.setAnimationStyle(R.style.AnimationFade);
            popupWindow.setFocusable(false);
            popupWindow.setOutsideTouchable(false);
            //避免个别机型上showAsDrioDown失效问题
            int[] locations = new int[2];
            titleBar.getLocationOnScreen(locations);
            int screenHeight = getApplicationContext().getResources().getDisplayMetrics().heightPixels;
            int height = screenHeight - titleBar.getHeight() - locations[1];
            popupWindow.setHeight(height);
        }

        if (!popShow) {
            popupWindow.showAsDropDown(titleBar, 0, 0);
            popShow = true;
        } else {
            popupWindow.dismiss();
            popShow = false;
        }
    }

    //获取权限
    public void getAuth() {

        final String name = SpUtil.getString(MainActivity.this, ConstanceHeTai.user_name);
        String murl = SpUtil.getString(MainActivity.this, ConstanceHeTai.login_server_address);
        String url = ConstanceHttp.base_url + murl + ConstanceHttp.sysabout_auth_list;
        OkHttpUtils.post().addParams("user", name).addParams("cacc_id", cacc_id).addParams("iyear", yearStr).url(url).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtil.showToast("服务器异常");
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    if (TextUtils.isEmpty(response)) {
                        ToastUtil.showToast("数据异常");
                    } else {
                        Gson gson = new Gson();
                        UserPermissionBean permissionBean = gson.fromJson(response, UserPermissionBean.class);
                        if (permissionBean != null) {
                            List<UserPermissionBean.AuthlistBean> authlist = permissionBean.getAuthlist();
                            if (authlist != null && !authlist.isEmpty()) {
                                for (int i = 0; i < authlist.size(); i++) {
                                    String cauth_id = authlist.get(i).getCauth_id() == null ? "" : authlist.get(i).getCauth_id();
                                    String cauth_name = authlist.get(i).getCauth_name() == null ? "" : authlist.get(i).getCauth_name();
                                    userauthlist.add(new UserAuth(cauth_id, cauth_name));
                                }
                            }
                            initByAuth();
                            //记录到全局变量中
                            if (userauthlist != null && userauthlist.size() > 0) {
                                myApplication.setGv_userauth(userauthlist);
                            }
                            //权限处理完成后，进行推送平台注册
                            //注册极光推送
                            registerMessageReceiver();
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });

//        String urlString = "http://" + InstorageURL.SERVERURL + BaseUrl_New;//旧版webservice地址
//        AbSoapParams params = new AbSoapParams();
//        params.put("arg0", User.uid);
//        params.put("arg1", myApplication.getGs_ztid());
//        params.put("arg2", myApplication.getGs_year());
//        mAbSoapUtil.call(urlString, InstorageURL.NAME_SPACE, "authlist", params, new AbSoapListener() {
//            //获取数据成功会调用这里
//            @Override
//            public void onSuccess(int statusCode, String content) {
//                if (content != null) {
//                    List<String> list = new ArrayList<String>();
//                    content = content.replace("UserAuth=anyType", "#=#");
//                    String[] strs = content.split("#=");
//                    for (int i = 0; i < strs.length; i++) {
//                        if (strs[i].contains("#")) {
//                            list.add(strs[i].replace("#", "").trim().replace(" ", ""));
//                        }
//                    }
//                    userauthlist = new ArrayList<UserAuth>();
//                    for (int i = 0; i < list.size(); i++) {
//                        if (i == list.size() - 1) {
//                            list.set(i, list.get(i).replace(";};};}", "\"}"));
//                        }
//                        list.set(i, list.get(i).replace(";};", "\"}").replace("=", "\":\"").replace(";", "\",\"")
//                                .replace("{cauth_id", "{\"cauth_id"));
//                        try {
//                            UserAuth info = new UserAuth();
//                            JSONObject dataJson = new JSONObject(list.get(i));
//                            info.setCauth_id(string2null(dataJson.getString("cauth_id")));
//                            info.setCauth_name(string2null(dataJson.getString("cauth_name")));
//                            userauthlist.add(info);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//                    initByAuth();
//                    //记录到全局变量中
//                    if (userauthlist != null && userauthlist.size() > 0) {
//                        myApplication.setGv_userauth(userauthlist);
//                    }
//                    //权限处理完成后，进行推送平台注册
//                    //注册极光推送
//                    registerMessageReceiver();
//
//                } else {
//                    AbToastUtil.showToast(MainActivity.this, R.string.sqlerrormsg);
//                }
//            }
//
//            // 失败，调用
//            @Override
//            public void onFailure(int statusCode, String content,
//                                  Throwable error) {
//                AbToastUtil.showToast(MainActivity.this, R.string.sqlerrormsg);
//            }
//        });
    }

    //根据权限初始化界面功能模块
    private void initByAuth() {
        inflater = LayoutInflater.from(this);
        params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        for (int i = 0; i < 8; i++) {//暂系统设计上 最多8大功能模块 （最多20个子模块）
            if (!modulecheck(i)) continue;

            List<Integer> childs = new ArrayList<>();
            switch (i) {
                case 0://请购管理模块
                    if (authcheck("QG02010301") || authcheck("QG020103")) {
                        childs.add(1);//部门请购定价
                    }
                    if (authcheck("QG02010401") || authcheck("QG020104")) {
                        childs.add(2);//部门请购审批
                    }
                    if (authcheck("QG020107") && mrqgd_usesp.equals("true")) {
                        childs.add(3);//厨房请购审批
                    }
                    if (authcheck("QG020108")) {
                        childs.add(4);//厨房请购清单
                    }
                    break;
                case 1://采购验收模块
                    if (authcheck("PG02020001")) {
                        childs.add(5);//请购生成订单
                    }
                    if (authcheck("PG02030001")) {
                        childs.add(6);//订单生成收货
                    }
                    if (authcheck("PG02030002")) {
                        childs.add(7);//订单生成直拨
                    }
                    break;
                case 2://库存管理模块
                    if (authcheck("KC020404") || authcheck("KC020104")) {
                        childs.add(8);//库存申请审批
                    }
                    break;
                case 3://应付管理模块
//                    if () {//新增子模块
//                        childs.add(9);//付款单审批
//                    }
                    break;
                case 4://集团管理模块
                    if (authcheck("JT0211")) {
                        childs.add(10);//集团请购审批
                    }
                    break;
                case 5://资产管理模块
                    if (authcheck("ZG0302")) {
                        childs.add(11);//资产盘点
                        childs.add(12);//资产查看
                    }
//                    if () {//新增子模块
//                        childs.add(13);//低易品盘点
//                    }
//                    if () {//新增子模块
//                        childs.add(14);//低易品查看
//                    }
                    break;
                case 6://工程维修模块
                    if (authcheck("WX0201")) {
                        childs.add(15);//工程报修
                    }
                    if (authcheck("WX0202")) {
                        childs.add(16);//维修接单
                    }
                    if (authcheck("WX0203")) {
                        childs.add(17);//维修销单
                    }
                    if (authcheck("WX0204")) {
                        childs.add(18);//维修审核
                    }
//                    if () {//新增子模块
//                        childs.add(19);//维修清单
//                    }
                    break;
                case 7://统计报表模块
//                    if () {//新增子模块
//                        childs.add(20);//工作日报表
//                    }
                    break;
            }

            addView(new Module(i + 1, childs));
        }
    }

    private void addView(Module module) {
        View view = inflater.inflate(R.layout.layout_item_a, null);
        TextView title = (TextView) view.findViewById(R.id.tv_main);
        CheckBox checkBox = (CheckBox) view.findViewById(R.id.cb_main);
        GridView gridView = (GridView) view.findViewById(R.id.gv_main);
        String tStr = "";
        switch (module.group) {
            case 1:
                tStr = "请购管理";
                break;
            case 2:
                tStr = "采购验收";
                break;
            case 3:
                tStr = "库存管理";
                break;
            case 4:
                tStr = "应付管理";
                break;
            case 5:
                tStr = "集团管理";
                break;
            case 6:
                tStr = "资产管理";
                break;
            case 7:
                tStr = "工程维修";
                break;
            case 8:
                tStr = "统计报表";
                break;
        }
        title.setText(tStr);
        MainItemGridAdapter adapter = new MainItemGridAdapter(this, module.childs);
        gridView.setAdapter(adapter);
        checkBox.setTag(adapter);
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                ((MainItemGridAdapter) buttonView.getTag()).scale(isChecked);
            }
        });

        ll_main.addView(view, params);
    }

    //模块检测
    public boolean modulecheck(int index) {
        switch (index) {
            case 0://请购管理权限
                if (authcheck("QG02010301") || authcheck("QG020103")) {
                    isModule0 = "true";
                    return true;
                }
                if (authcheck("QG02010401") || authcheck("QG020108")) {
                    isModule0 = "true";
                    return true;
                }
                if (authcheck("QG020104")) {
                    isModule0 = "true";
                    return true;
                }
                break;
            case 1://采购验收权限
                if (authcheck("PG02020001")) return true;
                if (authcheck("PG02030001")) return true;
                if (authcheck("PG02030002")) return true;
                break;
            case 2://库存管理权限
                if (authcheck("KC020404") || authcheck("KC020104")) return true;
                break;
            case 3://应付管理权限
                // TODO: 2018/8/23  新增模块
                break;
            case 4://集团管理权限
                if (authcheck("JT0211") && isJtgl == true && "true".equals(isModule0)) {
                    return true;
                }
                break;
            case 5://资产管理权限
                if (authcheck("ZG0302")) return true;
                break;
            case 6://工程维修权限
                if (authcheck("WX0201")) return true;
                if (authcheck("WX0202")) return true;
                if (authcheck("WX0203")) return true;
                if (authcheck("WX0204")) return true;
                break;
            case 7://统计报表权限
                // TODO: 2018/8/23  新增模块
                break;
        }
        return false;
    }

    //获取一些全局的参数设置,目前还不能分页
    private void getdata() {

        final String name = SpUtil.getString(MainActivity.this, ConstanceHeTai.user_code);
        String murl = SpUtil.getString(MainActivity.this, ConstanceHeTai.login_server_address);
        String url = ConstanceHttp.base_url + murl + ConstanceHttp.sysabout_options_list;
        OkHttpUtils.post().addParams("usercode", name).addParams("cacc_id", cacc_id).addParams("iyear", yearStr).url(url).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtil.showToast("服务器异常");
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    if (TextUtils.isEmpty(response)) {
                        ToastUtil.showToast("数据异常");
                    } else {
                        Gson gson = new Gson();
                        ParamsSettingBean settingBean = gson.fromJson(response, ParamsSettingBean.class);
                        if (settingBean != null) {

                            List<ParamsSettingBean.OptionslistBean> optionslistss = settingBean.getOptionslist();
                            if (optionslistss != null && !optionslistss.isEmpty()) {
                                for (ParamsSettingBean.OptionslistBean optionslistBean : optionslistss) {


                                    UffjOptions info = new UffjOptions();

                                    info.setID(string2null(optionslistBean.getID()));
                                    info.setDd_num(string2null(optionslistBean.getDd_num()));
                                    info.setQgd_num(string2null(optionslistBean.getQgd_num()));
                                    info.setShd_num(string2null(optionslistBean.getShd_num()));
                                    info.setYffp_num(string2null(optionslistBean.getYffp_num()));
                                    info.setShd_dep(string2null(optionslistBean.getShd_dep()));
                                    info.setAp_ccode_c(string2null(optionslistBean.getAp_ccode_c()));
                                    info.setAp_ccode_d(string2null(optionslistBean.getAp_ccode_d()));
                                    info.setShd_rdincode(string2null(optionslistBean.getShd_rdincode()));
                                    info.setZbd_rdincode(string2null(optionslistBean.getZbd_rdincode()));
                                    info.setZbd_rdoutcode(string2null(optionslistBean.getZbd_rdoutcode()));
                                    info.setSh_check_close(string2null(optionslistBean.getSh_check_close()));
                                    info.setPrice(string2null(optionslistBean.getPrice()));
                                    info.setSh_rd_check(string2null(optionslistBean.getSh_rd_check()));
                                    info.setRow_num(string2null(optionslistBean.getRow_num()));
                                    info.setPrint_unit(string2null(optionslistBean.getPrint_unit()));
                                    info.setPrint_taoda(string2null(optionslistBean.getPrint_taoda()));
                                    info.setQgd_dd_check(string2null(optionslistBean.getQgd_dd_check()));
                                    info.setZbd_cwhcode(string2null(optionslistBean.getZbd_cwhcode()));
                                    info.setRd_rdoutcode(string2null(optionslistBean.getRd_rdoutcode()));
                                    info.setShd_rdinname(string2null(optionslistBean.getShd_rdinname()));
                                    info.setZbd_rdinname(string2null(optionslistBean.getZbd_rdinname()));
                                    info.setZbd_rdoutname(string2null(optionslistBean.getZbd_rdoutname()));
                                    MainActivity.this.optionslist.add(info);


                                }

                            }
                            if (optionslist != null && optionslist.size() > 0) {
                                for (int i = 0; i < optionslist.size(); i++) {
                                    UffjOptions option = optionslist.get(i);
                                    if (option.getID().equals("1")) {
                                        //参数设置到缓存
                                        myApplication.setGs_option1(option);
                                    }
                                    if (option.getID().equals("2")) {
                                        //参数设置到缓存
                                        myApplication.setGs_option2(option);
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });


//        String urlString = "http://" + InstorageURL.SERVERURL + BaseUrl_New;//旧版webservice地址
//        AbSoapParams params = new AbSoapParams();
//        params.put("arg0", User.uid);
//        params.put("arg1", myApplication.getGs_ztid());
//        params.put("arg2", myApplication.getGs_year());
//        mAbSoapUtil.call(urlString, InstorageURL.NAME_SPACE, "optionslist", params, new AbSoapListener() {
//            //获取数据成功会调用这里
//            @Override
//            public void onSuccess(int statusCode, String content) {
//                if (content != null) {
//                    List<String> list = new ArrayList<String>();
//                    optionslist = new ArrayList<UffjOptions>();
//                    content = content.replace("UffjOptions=anyType", "#=#");
//                    String[] strs = content.split("#=");
//                    for (int i = 0; i < strs.length; i++) {
//                        if (strs[i].contains("#")) {
//                            list.add(strs[i].replace("#", "").trim().replace(" ", ""));
//                        }
//                    }
//                    for (int i = 0; i < list.size(); i++) {
//                        if (i == list.size() - 1) {
//                            list.set(i, list.get(i).replace(";};};}", "\"}"));
//                        }
//                        list.set(i, list.get(i).replace(";};", "\"}").replace("=", "\":\"").replace(";", "\",\"").replace("{I", "{\"I"));
//                        try {
//                            UffjOptions info = new UffjOptions();
//                            JSONObject dataJson = new JSONObject(list.get(i));
//                            info.setID(string2null(dataJson.getString("ID")));
//                            info.setDd_num(string2null(dataJson.getString("dd_num")));
//                            info.setQgd_num(string2null(dataJson.getString("qgd_num")));
//                            info.setShd_num(string2null(dataJson.getString("shd_num")));
//                            info.setYffp_num(string2null(dataJson.getString("yffp_num")));
//                            info.setShd_dep(string2null(dataJson.getString("shd_dep")));
//                            info.setAp_ccode_c(string2null(dataJson.getString("ap_ccode_c")));
//                            info.setAp_ccode_d(string2null(dataJson.getString("ap_ccode_d")));
//                            info.setShd_rdincode(string2null(dataJson.getString("shd_rdincode")));
//                            info.setZbd_rdincode(string2null(dataJson.getString("zbd_rdincode")));
//                            info.setZbd_rdoutcode(string2null(dataJson.getString("zbd_rdoutcode")));
//                            info.setSh_check_close(string2null(dataJson.getString("sh_check_close")));
//                            info.setPrice(string2null(dataJson.getString("price")));
//                            info.setSh_rd_check(string2null(dataJson.getString("sh_rd_check")));
//                            info.setRow_num(string2null(dataJson.getString("row_num")));
//                            info.setPrint_unit(string2null(dataJson.getString("print_unit")));
//                            info.setPrint_taoda(string2null(dataJson.getString("print_taoda")));
//                            info.setQgd_dd_check(string2null(dataJson.getString("qgd_dd_check")));
//                            info.setZbd_cwhcode(string2null(dataJson.getString("zbd_cwhcode")));
//                            info.setRd_rdoutcode(string2null(dataJson.getString("rd_rdoutcode")));
//                            info.setShd_rdinname(string2null(dataJson.getString("shd_rdinname")));
//                            info.setZbd_rdinname(string2null(dataJson.getString("zbd_rdinname")));
//                            info.setZbd_rdoutname(string2null(dataJson.getString("zbd_rdoutname")));
//                            optionslist.add(info);
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                    if (optionslist != null && optionslist.size() > 0) {
//                        for (int i = 0; i < optionslist.size(); i++) {
//                            UffjOptions option = optionslist.get(i);
//                            if (option.getID().equals("1")) {
//                                //参数设置到缓存
//                                myApplication.setGs_option1(option);
//                            }
//                            if (option.getID().equals("2")) {
//                                //参数设置到缓存
//                                myApplication.setGs_option2(option);
//                            }
//                        }
//                    }
//                } else {
//                    AbToastUtil.showToast(MainActivity.this, R.string.sqlerrormsg);
//                }
//            }
//
//            // 失败，调用
//            @Override
//            public void onFailure(int statusCode, String content,
//                                  Throwable error) {
//                AbToastUtil.showToast(MainActivity.this, R.string.sqlerrormsg);
//            }
//
//        });
    }

    private void czzcorp_list() {
        String nameSpace = "http://service.test.com";
        String urlString = "http://" + InstorageURL.SERVERURL + BaseUrl_New;
        String methodName = "getaccinformation";
        AbSoapParams params = new AbSoapParams();
        params.put("arg0", myApplication.getGs_ztid());
        params.put("arg1", myApplication.getGs_year());
        params.put("arg2", "QG");
        params.put("arg3", "mrqgd_usesp");
        mAbSoapUtil.call(urlString, nameSpace, methodName, params, new AbSoapListener() {
            //获取数据成功会调用这里
            @Override
            public void onSuccess(int statusCode, String content) {
                if (content != null) {
                    String res = content.split("=")[1].split(";")[0];
                    if (res.equals("anyType{}") || res.equals("")) {
                        mrqgd_usesp = "false";
                    } else {
                        mrqgd_usesp = res;
                    }
                } else {
                    AbToastUtil.showToast(MainActivity.this, R.string.sqlerrormsg);
                }
            }

            // 失败，调用
            @Override
            public void onFailure(int statusCode, String content,
                                  Throwable error) {
                AbToastUtil.showToast(MainActivity.this, R.string.toast_server_error);
            }

        });

        String nameSpace2 = "http://service.test.com";
        String urlString2 = "http://" + InstorageURL.SERVERURL + BaseUrl_New;
        String methodName2 = "czzcorp_list";
        AbSoapParams params2 = new AbSoapParams();
        params2.put("arg0", myApplication.getGs_ztid());
        params2.put("arg1", myApplication.getGs_year());
        mAbSoapUtil.call(urlString2, nameSpace2, methodName2, params2, new AbSoapListener() {
            //获取数据成功会调用这里
            @Override
            public void onSuccess(int statusCode, String content) {
                if (content != null) {
                    String str = content.split("czzcorp_listResponse")[1];
                    if ("{out=anyType{}; }".equals(str)) {
                        isJtgl = false;
                    } else {
                        isJtgl = true;
                    }
                } else {
                    AbToastUtil.showToast(MainActivity.this, R.string.sqlerrormsg);
                }
            }

            @Override
            public void onFailure(int statusCode, String content,
                                  Throwable error) {
                AbToastUtil.showToast(MainActivity.this, R.string.toast_server_error);
            }

        });
    }

    //权限检测
    public boolean authcheck(String auth) {
        Boolean haveauth = false;
        for (int j = 0; j < userauthlist.size(); j++) {
            UserAuth authdetail = userauthlist.get(j);
            if (authdetail.authfind(auth)) {
                //找到对应权限则返回
                haveauth = true;
                break;
            }
        }
        return haveauth;
    }

    public void registerMessageReceiver() {
        authmenus = "";
        if (authcheck("QG02010301") || authcheck("QG020103"))
            authmenus = authmenus + "qgddjlist,";//部门请购定价
        if (authcheck("QG02010401") || authcheck("QG020104"))
            authmenus = authmenus + "qgdsplist,";//部门请购审批
        if (authcheck("QG020107")) {
            if (mrqgd_usesp.equals("true")) {
                authmenus = authmenus + "mrqgdsplist,";//厨房请购审批
            } else {
                authmenus = authmenus + "mrqgdchecklist,";//厨房请购审核
            }
        }
        if (authcheck("QG020108")) authmenus = authmenus + "mrqgdlist,";//厨房请购叫货，定价
        if (authcheck("PG02020001")) authmenus = authmenus + "qgddlist,";//采购管理请购订单
        if (authcheck("PG02030001")) authmenus = authmenus + "ddshlist,";//订单收货
        if (authcheck("PG02030002")) authmenus = authmenus + "ddzblist,";//订单直拨
        if (authcheck("KC020404") || authcheck("KC020104"))
            authmenus = authmenus + "kcapplist,";   //功能：库存申请审批//后一个权限是8.0
        if (authcheck("WX0201")) authmenus = authmenus + "wxbxlist,";//部门报修
        if (authcheck("WX0202")) authmenus = authmenus + "wxjdlist,";//维修接单
        if (authcheck("WX0203")) authmenus = authmenus + "wxxdlist,";//维修销单
        if (authcheck("WX0204")) authmenus = authmenus + "wxchecklist,";//维修审核
        if (authcheck("ZG0302")) authmenus = authmenus + "zcpdlist,";//资产盘点
        if (authcheck("JT0211")) authmenus = authmenus + "jtsplist,";//集团审批

        mMessageReceiver = new JiGuangReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        registerReceiver(mMessageReceiver, filter);
        JPushInit();  // used for receive msg
    }

    // 极光推送
    // 初始化JPush。如果已经初始化，但没有登录成功，则执行重新登录。
    private void JPushInit() {
        //设备注册
        AbTask task = new AbTask();
        final AbTaskItem item = new AbTaskItem();
        item.setListener(new AbTaskObjectListener() {

            @Override
            public <T> void update(T entity) {
                String nameSpace = "http://service.test.com";
                String urlString = "http://" + InstorageURL.SERVERURL + BaseUrl_New;
                String methodName = "DeviceLogin";
                AbSoapParams params = new AbSoapParams();
                params.put("arg0", User.uid);
                params.put("arg1", User.nickName);
                params.put("arg2", myApplication.getGs_ztid());
                params.put("arg3", myApplication.getGs_year());
                params.put("arg4", myApplication.getGs_sj());
                params.put("arg5", regId1);
                params.put("arg6", "Android");
                params.put("arg7", authmenus);
                mAbSoapUtil.call(urlString, nameSpace, methodName, params, new AbSoapListener() {
                    //获取数据成功会调用这里
                    @Override
                    public void onSuccess(int statusCode, String content) {
                        if (content != null) {
                            ToolLog.log("**************res:" + content);
                        } else {
                            AbToastUtil.showToast(MainActivity.this, R.string.deviceloginerror);
                        }
                    }

                    // 失败，调用
                    @Override
                    public void onFailure(int statusCode, String content,
                                          Throwable error) {
                        AbToastUtil.showToast(MainActivity.this, R.string.sqldeviceloginerror);
                    }

                    // 开始执行前
                    @Override
                    public void onStart() {
                        //显示进度框
                    }

                    // 完成后调用，失败，成功
                    @Override
                    public void onFinish() {
                        //移除进度框
                        AbDialogUtil.removeDialog(MainActivity.this);
                    }
                });
            }

            @SuppressWarnings("unchecked")
            @Override
            public Integer getObject() {
                return -1;
            }
        });
        task.execute(item);
    }

    @Override
    protected void onResume() {
        isForeground = true;
        super.onResume();
    }

    @Override
    protected void onPause() {
        isForeground = false;
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        //取消设备注册
        String nameSpace = "http://service.test.com";
        String urlString = "http://" + InstorageURL.SERVERURL + BaseUrl_New;
        String methodName = "DeviceLoginOut";
        AbSoapParams params = new AbSoapParams();
        params.put("arg0", regId1);
        mAbSoapUtil.call(urlString, nameSpace, methodName, params, new AbSoapListener() {
            //获取数据成功会调用这里
            @Override
            public void onSuccess(int statusCode, String content) {
                if (content != null) {
                    ToolLog.log("**************res:" + content);
                } else {
                    AbToastUtil.showToast(MainActivity.this, R.string.deviceloginerror);
                }
            }

            // 失败，调用
            @Override
            public void onFailure(int statusCode, String content,
                                  Throwable error) {
                AbToastUtil.showToast(MainActivity.this, R.string.sqldeviceloginerror);
            }
        });

        JPushInterface.clearAllNotifications(getApplicationContext());//关闭已提示消息
        if (mMessageReceiver!=null){
            unregisterReceiver(mMessageReceiver);
        }
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (popupWindow != null && popupWindow.isShowing())
            popupWindow.dismiss();
        super.onBackPressed();
    }

    public class Module {//功能模块

        public int group;
        public List<Integer> childs;

        public Module(int group, List<Integer> childs) {
            this.group = group;
            this.childs = childs;
        }
    }

}